package com.inspur.sc.springboot.controller;

import com.inspur.sc.springboot.entity.SysMenu;
import com.inspur.sc.springboot.entity.SysUser;
import com.inspur.sc.springboot.service.SysMenuService;
import com.inspur.sc.springboot.utils.MenuUtil;
import com.inspur.sc.springboot.utils.ResponseUtil;
import com.inspur.sc.springboot.utils.SpringSecurityUtils;
import com.inspur.sc.springboot.vo.ResponseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("api/menu")
public class SysMenuController {

    @Autowired
    private SysMenuService menuService;

    @GetMapping("findAll")
    public ResponseEntity<ResponseVO> findAll(){
        List<SysMenu> menus=menuService.findAll();
        if(!menus.isEmpty()){
            return ResponseUtil.success(MenuUtil.getMenuJson(menus,false));
        }
        return ResponseUtil.success(null);
    }


    @PostMapping("save")
    public ResponseEntity<ResponseVO> save(@RequestBody SysMenu menu){
        boolean isSave=menuService.save(menu);
        if(isSave){
            return ResponseUtil.success("保存成功",true);
        }
        return ResponseUtil.success("保存失败",false);
    }

    @GetMapping("delete")
    public ResponseEntity<ResponseVO> save(@RequestParam(value = "id") Integer id){
        boolean isDel=menuService.delete(id);
        if(isDel){
            return ResponseUtil.success("删除成功",true);
        }
        return ResponseUtil.success("删除失败",false);
    }

    @GetMapping("get")
    public ResponseEntity<ResponseVO> get(@RequestParam(value = "id") Integer id){
        return ResponseUtil.success(menuService.findSysMenuById(id));
    }


    @GetMapping("/findSysMenuByUserId")
    public ResponseEntity<ResponseVO> findSysPermissionByUserId(HttpServletRequest request){
        Authentication authentication= SpringSecurityUtils.getAuthentication(request);
        SysUser user= (SysUser) authentication.getPrincipal();
        List<SysMenu> menuList=menuService.findSysMenuByUId(user.getId());
        if(!menuList.isEmpty()){
            return ResponseUtil.success(MenuUtil.getMenuJson(menuList,true));
        }
        return ResponseUtil.success(null);
    }

}
